// 游戏管理器
import LoadingPage from '../ui/LoadingPage.js';
import DailyRewardPage from '../ui/DailyRewardPage.js';
import MainPage from '../ui/MainPage.js';
import GamePage from '../ui/GamePage.js';
import GameOverPage from '../ui/GameOverPage.js';
import ProfilePage from '../ui/ProfilePage.js';
import RankingListPage from '../ui/RankingListPage.js';
const api = require('../api/index.js');
const rootImgUrl = 'http://121.196.204.249/images/'

class GameManager {
  constructor(canvas, ctx) {
    this.canvas = canvas;
    this.ctx = ctx;
    this.currentPage = null;
    this.userData = null;
    this.pages = {};
  }

  async init() {
    wx.login({
      success: (res) => {
        if (res.code) {
          // 调用你的后台接口，用 code 换取自定义登录态（openid）
          api.user.login(res.code).then(data => {
            let info = JSON.parse(data)
            // 保存openid等操作
            wx.setStorageSync('open_id', info.openid);
            // 加载用户数据
            this.loadUserData();
          }).catch(err => {
            console.error('登录失败:', err);
          });
        } else {
          console.error('wx.login 调用失败!', res.errMsg);
        }
      }
    });

    // 绑定事件
    this.bindEvents();
    // 初始化所有页面
    await this.initPages();
    // 启动游戏循环
    this.gameLoop();
  }

  loadUserData() {
    try {
      const savedData = wx.getStorageSync('userData');
      if (savedData) {
        this.userData = savedData;
      } else {
        api.user.getUserProfile().then(data => {
          console.log('用户信息:', data);
          wx.setStorageSync('userData', data);
        }).catch(err => {
          console.error('获取用户信息失败:', err);
        });
      }
    } catch (e) {
      console.log('加载用户数据失败:', e);
    }
  }

  saveUserData() {
    try {
      wx.setStorageSync('userData', this.userData);
    } catch (e) {
      console.log('保存用户数据失败:', e);
    }
  }

  async initPages() {
    // 初始化所有页面
    this.pages = {
      loading: new LoadingPage(this.canvas, this.ctx, this, api, rootImgUrl),
      dailyReward: new DailyRewardPage(this.canvas, this.ctx, this, api, rootImgUrl),
      main: new MainPage(this.canvas, this.ctx, this, api, rootImgUrl),
      game: new GamePage(this.canvas, this.ctx, this, api, rootImgUrl),
      gameOver: new GameOverPage(this.canvas, this.ctx, this, api, rootImgUrl),
      profile: new ProfilePage(this.canvas, this.ctx, this, api, rootImgUrl),
      ranking: new RankingListPage(this.canvas, this.ctx, this, api, rootImgUrl)
    };

    // 设置初始页面
    this.switchPage('loading');
  }

  switchPage(pageName) {
    if (this.currentPage) {
      this.currentPage.onLeave();
    }

    this.currentPage = this.pages[pageName];
    this.currentPage.onEnter();
  }

  bindEvents() {
    // 触摸事件
    wx.onTouchStart((e) => {
      const touchStart = e.touches[0];
      this.currentPage.handleTouch(touchStart.clientX, touchStart.clientY);
    });

    wx.onTouchMove((e) => {
      const touchMove = e.touches[0];
      this.currentPage.handleTouchMove(touchMove.clientX, touchMove.clientY);
    })

    wx.onTouchEnd((e) => {
      this.currentPage.handleTouchEnd(e);
    })

    wx.onTouchCancel((e) => {
      const touch = e.touches[0];
      //this.currentPage.handleTouchCancel(touch.clientX, touch.clientY);
    })

    // 键盘事件
    wx.onKeyDown((e) => {
      this.currentPage.handleKeyDown(e);
    });
  }

  gameLoop() {
    this.update();
    this.render();
    requestAnimationFrame(() => this.gameLoop());
  }

  update() {
    this.currentPage.update();
  }

  render() {
    this.currentPage.render();
  }

  getUserData() {
    return this.userData;
  }

  updateUserData(newData) {
    this.userData = { ...this.userData, ...newData };
    this.saveUserData();
  }
}

export default GameManager;